import { log } from 'console';
import { dicts, generateDict } from './dictionary';
/**
 *@auther: tang
 *@Date: 2021-01-29
 *Project: p2pPlatformSys
 *Lang: TypeScript
 */

const dayjs = require('dayjs');
const fs = require('fs');
const path = require('path');
import { Sequelize } from 'sequelize';
const { Op } = require('sequelize');
export const generateDictionary = generateDict;
export const dictionary = dicts;
export function getNowTime() {
  const time = new Date();
  return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`;
}
// 获取今天
export function getTodayTime() {
  const time = new Date();
  return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate() > 10 ? '0' + time.getDate() : time.getDate()}`;
}
// 计算上个月
export function calcLastMonth(time) {
  const nowMonth = (new Date(time)).getFullYear() + '-' + ((new Date(time).getMonth() + 1) < 10 ? '0' + (new Date(time).getMonth() + 1) : (new Date(time).getMonth() + 1));
  const month = new Date(nowMonth).getMonth() + 1;
  const year = new Date(nowMonth).getFullYear();
  // console.log(nowMonth, month, year);
  let lastMonth:any = '',
    lastYear:any = '';
  if (Number(month) === 1) {
    lastMonth = 12;
    lastYear = year - 1;
  } else {
    lastMonth = month - 1;
    lastYear = year;
  }
  return lastYear + '-' + (lastMonth < 10 ? '0' + lastMonth : lastMonth);
}
export function getMonthTime() {
  const time = new Date();
  return `${time.getFullYear()}-${(time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1)}`;
}
export function calcFileHref(fileNameInp:string) {
  const uplaodBasePath = 'app/public/upload/';
  // 生成文件名
  const filename:string = Date.now() + '' + Number.parseInt(String(Math.random() * 10000)) + path.extname(fileNameInp);
  // 生成文件夹
  const dirName = dayjs(Date.now()).format('YYYYMMDD');
  // 判断文件夹是否存在，不存在则直接创建文件夹
  if (!fs.existsSync(path.join(uplaodBasePath, dirName))) fs.mkdirSync(path.join(uplaodBasePath, dirName));
  // 生成写入路径
  return path.join(uplaodBasePath, dirName, filename);
}
export function generateObjArr(dataParams:object[], dataOrigin:object[]) {
  const origin:object[] = JSON.parse(JSON.stringify(dataOrigin));
  for (const i in origin) {
    if (dataParams[i] != null && dataParams[i] !== undefined) {
      origin[i] = dataParams[i];
    }
  }
  return origin;
}
export function clearObj(oriData:any[]):object[] {
  const origin = JSON.parse(JSON.stringify(oriData));
  for (const oriDataKey in origin) {
    origin[oriDataKey] = null;
  }
  return origin;
}
export function clearNullItems(oriData:any[]):object[] {
  const origin = JSON.parse(JSON.stringify(oriData));
  for (const oriKey in origin) {
    if (origin[oriKey] === null) {
      delete origin[oriKey];
    }
  }
  return origin;
}
export function getDateNumber() {
  const date = new Date();
  const dateNumber = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + '' + date.getMilliseconds() + '' + date.getTime();
  return dateNumber;
}
export function generateQueryArr(params: object[]) {
  log(params);
  const newPar = JSON.parse(JSON.stringify(params));
  const newArr = [];
  if (newPar) {
    for (const i in newPar) {
      const newObj: any = {};
      newObj[i] = {
        [Op.like]: '%' + newPar[i] + '%',
      };
      newArr.push(newObj as never);
    }

  }
  return {
    [Op.and]: newArr,
  };
}
// 首字母大写
export function upperFirst(s) {
  return s.toLowerCase().replace(/\b([\w|‘]+)\b/g, function(word) {
    // return word.slice(0, 1).toUpperCase() + word.slice(1);
    return word.replace(word.charAt(0), word.charAt(0).toUpperCase());
  });
}
// 生成投资单号
export function generateserId() {
  return Date.now() + '' + Number.parseInt(String(Math.random() * 10000)) + dayjs(Date.now()).format('YYYYMMDDHHmmss');
}

export async function addPlatMsg(instance, nowId, msg) {
  const { ctx } = instance;
  console.log(ctx.state.user);
  const user = ctx.state.user;
  let target = '',
    duid = 0,
    puid = 0,
    ivid = 0;
  dictionary.forEach(item => {
    if (item[0] === ctx.request.url) {
      target = item[4];
      switch (user.userType) {
        case 'platform':
          puid = user.id;
          break;
        case 'debitUser':
          duid = user.id;
          break;
        case 'investUser':
          ivid = user.id;
          break;
        default:
          break;
      }
    }
  });
  const message = await ctx.service.home.addMessage({
    msg,
    time: getNowTime(),
    targetSource: target,
    isview: 0,
    duid,
    puid,
    ivid,
  });
  const mid = message.null;
  dictionary.forEach(item => {
    if (item[0] === ctx.request.url) {
      ctx.model[upperFirst(item[2])].update({
        mid,
      }, { where: { id: nowId } });
    }
  });
}
export async function hasReadMsg(instance, mid) {
  const { ctx } = instance;
  if (mid) {
    await ctx.model.Messages.update({ isview: 1 }, { where: { id: mid } });
  }
}
// 连接数据库的sequelize实例
export async function getSeqIns(ins) {
  const { ctx } = ins;
  return new Sequelize({ ...ctx.app.config.sequelize });
}

export function generateCharts(sourceArr:Array<any>, reparam:string, param:string) {
  const dbData:Array<any> = [];
  let nowPs = 0;
  let nowMonth = getMonthTime();
  try {
    for (let i = 0; i < 12; i++) {
      // console.log(allInvest[nowPs].TIME, nowMonth);
      if (sourceArr[nowPs] && sourceArr[nowPs].TIME && sourceArr[nowPs].TIME === nowMonth) {
        dbData.push({ time: sourceArr[nowPs].TIME, [reparam]: sourceArr[nowPs][param] || 0 });
        nowPs += 1;
      } else {
        dbData.push({ time: nowMonth, [reparam]: 0 });
        //  数据中没有这一项，要空出来
      }
      nowMonth = calcLastMonth(nowMonth);
    }
  } catch (e) {
    console.log(e);
  }
  return dbData;
}
